package com.cuotoniu.lazybug.common.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Encrypt the String
 * 
 * @author HLJ
 *
 */
public class EncryptUtil {

	private static MessageDigest md5;	/** MD5 encrypt */
	private static MessageDigest sha;	/** SHA encrypt */
	
	/** @throws NoSuchAlgorithmException */
	private static MessageDigest getStaticMD5() throws NoSuchAlgorithmException{
		if(md5 == null )
			md5 = MessageDigest.getInstance("MD5");
		return md5;
	}
	
	private static MessageDigest getStaticSHA() throws NoSuchAlgorithmException{
		if(sha == null )
			sha = MessageDigest.getInstance("SHA");
		return sha;
	}
	
	/**
	 * Encrypt the content by MD5 model
	 * 
	 * @param content
	 * @return
	 */
	public static String encryptByMD5(String content){
		byte[] obj = content.getBytes();
		try {
			md5 = getStaticMD5();
			md5.update(obj);
			byte[] result = md5.digest();
			String contentResult = "";
			for (int i = 0; i < result.length; i++) {
			    String tmp = Integer.toHexString(result[i] & 0xFF);
			    if (tmp.length() == 1) {
			    	contentResult += "0" + tmp;
			    } else {
			    	contentResult += tmp;
			    }
			}
			return contentResult;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	 
	/**
	 * Encrypt the content by SHA model
	 * 
	 * @param content
	 * @return
	 */
	public static String encryptBySHA(String content){
		byte[] obj = content.getBytes();
		try {
			sha = getStaticSHA();
			sha.update(obj);
			byte[] result = sha.digest();
			String contentResult = "";
			for (int i = 0; i < result.length; i++) {
			    String tmp = Integer.toHexString(result[i] & 0xFF);
			    if (tmp.length() == 1) {
			    	contentResult += "0" + tmp;
			    } else {
			    	contentResult += tmp;
			    }
			}
			return contentResult;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public static void main(String[] args) {
		String pwd = encryptByMD5("root");
		System.out.println(pwd);
		System.out.println(pwd.length());
	}
	
}
